package goods

import (
	"gorm.io/gorm"
	"shop/formdata"
	goods1 "shop/internal/models/goods"
	"shop/pkg"
)

type GoodsListByGoodsId struct {
	GoodsID  int64  `json:"goods_id"`
	Name     string `json:"name"`
	Price    string `json:"price"`
	VipPrice string `json:"vip_price"`
	Img      string `json:"img"`
}

// getAllTypeIDs 递归获取所有子分类 ID
func getAllTypeIDs(goodsType *goods1.Types, typeIDs []int64) ([]int64, error) {
	typeIDs = append(typeIDs, int64(goodsType.ID))
	childTypes, err := goodsType.SearchByIDs([]int64{int64(goodsType.ID)})
	if err != nil {
		return nil, err
	}
	for _, child := range childTypes {
		goodsType = &goods1.Types{
			Model:    gorm.Model{ID: child.ID},
			Icon:     child.Icon,
			Lv:       child.Location,
			Pid:      child.Pid,
			Name:     child.Name,
			Location: child.Location,
		}
	}

	return typeIDs, nil
}

func ListByGoodsIds(goodsTypes formdata.GoodsList) ([]*GoodsListByGoodsId, error) {
	types := goods1.Types{
		Model: gorm.Model{ID: uint(goodsTypes.TypeID)},
	}

	var typesID []int64
	if goodsTypes.TypeID != 0 && goodsTypes.TypeID != 1 {
		typesID, _ = getAllTypeIDs(&types, typesID)
	}
	goodsTitle, err := new(goods1.Goods).GoodsSearchByGoodsTitle(goodsTypes.Title, int(goodsTypes.Page), int(goodsTypes.PageSize), typesID)
	if err != nil {
		return nil, err
	}

	var goodsList []*GoodsListByGoodsId
	var sku goods1.GoodsSku
	for _, v := range goodsTitle {
		skuByGoodsId, err := sku.SearchSkuByGoodsId(int(v.ID))
		if err != nil {
			return nil, err
		}
		getImages := pkg.GetImages(v.Img)
		goodsList = append(goodsList, &GoodsListByGoodsId{
			GoodsID:  int64(v.ID),
			Name:     v.Title,
			Img:      getImages[0],
			Price:    skuByGoodsId.Price,
			VipPrice: skuByGoodsId.VipPrice,
		})

	}

	return goodsList, nil
}
